﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using EnterpriseManagement;
using EnterpriseManagement.Models;

namespace EnterpriseManagement.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult LogOn()
        {
            ////**********Bug***********////
            //string a = Request.Cookies[0].Value ;
            if (User.Identity.IsAuthenticated)
            {
                return View("MainPage");
            }
            return View();
        }

        //returnUrl is not initialized,this should be set in the global
        [HttpPost]
        public ActionResult LogOn(LogOnModel model,string returnUrl)
        {
            if (ModelState.IsValid)
            {
               if (FormsService .ValidateUser(model.UserName  , model.Password ))
                {
                    FormsService.SignIn(model.UserName  ,model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return View("MainPage");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }
            return View();
        }

        [Authorize]
        [HttpGet]
        public ActionResult BasicInformation()
        {
            string id = HttpContext.User.Identity.Name;
            Employee employee = FormsService.GetEmployeeByUserName(id);
            if (employee == null)
            {
                ModelState.AddModelError("UserError", "Can not get employee informtion relate to the user");
                return View();
            }
            BasicInformationModel model = new BasicInformationModel(employee);
           
            return PartialView("BasicInformation",model );
        }

        [Authorize]
        [HttpPost ]
        public ActionResult BasicInformation(BasicInformationModel model,string id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                    id = HttpContext.User.Identity.Name;
                if (Request.IsAjaxRequest())
                {
                    Employee e = FormsService.GetEmployeeByUserName(id);
                    if (e == null)
                    {
                        ViewData["ErrorMessage"] = "该员工不存在";
                        return PartialView("ErrorPage");
                    }
                    Employee employee = new Employee(model);
                    //employee.employee_id = e.employee_id;
                    if (FormsService.ChangeBasicInformation(employee))
                    {
                        ViewData["AlertMessage"] = "修改成功";
                        return PartialView("BasicInformation", model);
                    }
                    else
                    {
                        ViewData["AlertMessage"] ="修改个人信息失败";
                        return PartialView("BasicInformation", model);
                    }
                }
                else
                {
                    ViewData["ErrorMessage"] = "你没有权限";
                    return PartialView("ErrorPage");
                }
            }
            else
            {
                return PartialView("BasicInformation", model);
            }
        }

        public ActionResult Register()
        {
            List<string> position = FormsService.GetAllPositions();
            SelectList positionList = new SelectList(position);
            ViewData["Position"] = positionList;

            List<string> employeestatus = new List<string>();
            employeestatus.Add("On");
            employeestatus.Add("Off");
            SelectList employeestatusList = new SelectList(employeestatus);
            ViewData["EmployeeStatus"] = employeestatusList;

            List<string> sex = new List<string>();
            sex.Add("F");
            sex.Add("M");
            SelectList Sex = new SelectList(sex);
            ViewData["Sex"] = Sex;

            return PartialView("Register");
        }

        [HttpPost]
        [Authorize]
        public ActionResult Register(RegisterModel model)
        {
            List<string> position = FormsService.GetAllPositions();
            SelectList positionList = new SelectList(position);
            ViewData["Position"] = positionList;

            List<string> employeestatus = new List<string>();
            employeestatus.Add("On");
            employeestatus.Add("Off");
            SelectList employeestatusList = new SelectList(employeestatus);
            ViewData["EmployeeStatus"] = employeestatusList;

            List<string> sex = new List<string>();
            sex.Add("F");
            sex.Add("M");
            SelectList Sex = new SelectList(sex);
            ViewData["Sex"] = Sex;

            if (ModelState.IsValid)
            {
                if (Request.IsAjaxRequest())
                {
                    MembershipCreateStatus createResult = FormsService.CreateEmployee(model);
                    if (createResult == MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError(string.Empty, "创建成功");
                        return PartialView("Register", model);
                    }
                    else
                    {
                        ModelState.AddModelError("error", AccountValidation.ErrorCodeToString(createResult));
                        return PartialView("Register", model);
                    }
                }
                else
                {
                    ViewData["ErrorMessage"] = "你没有权限";
                    return PartialView("ErrorPage");
                }
            }
            else
            {
                return PartialView("Register");
            }
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("LogOn");
        }

        /// <summary>
        /// 只能修改自己的密码，管理员只能重置员工密码
        /// </summary>
        /// <param name="model"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel  model,string id)
        {
            if (ModelState.IsValid)
            {
                if (Request.IsAjaxRequest())
                {
                    if (FormsService.ChangePassword(model.OldPassword, model.NewPassword))
                    {
                        ModelState.AddModelError(string.Empty, "修改成功");
                        return PartialView(model);
                    }

                    ModelState.AddModelError(string.Empty, "账号或密码错误，修改失败");
                    return PartialView(model);
                }
                else 
                {
                    ViewData ["ErrorMessage"]="你没有权限进行此操作";
                    return PartialView("ErrorPage");
                }
            }
            else
            {
                return PartialView(model);
            }
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return PartialView();
        }

        [AuthorizeGroup(Group="Super")]
        public ActionResult ResetPassword()
        {
            return PartialView();
        }

        [HttpPost]
        [AuthorizeGroup(Group = "Super")]
        public ActionResult ResetPassword(RestPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.ResetPassowrd(model.EmployeeId, model.NewPassword))
                {
                    ModelState.AddModelError(string.Empty, "重置成功");
                    return PartialView();
                }
                ModelState.AddModelError(string.Empty, "重置失败，请检查输入信息后再操作");
            }
            return PartialView();
        }

        [AuthorizeGroup(Group = "Super")]
        public ActionResult DeleteUser()
        {
            return PartialView();
        }

        [HttpPost]
        [AuthorizeGroup(Group = "Super")]
        public ActionResult DeleteUser(DeleteUserModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.DeleteUser(model.EmployeeId, model.SuperPassword) == MembershipDeleteStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, "删除成功");
                    return PartialView();
                }
                ModelState.AddModelError(string.Empty, "删除失败，该ID不存在登录账号或输入信息有误");
            }
            return PartialView();
        }

        //[AuthorizeGroup(Group = "Super")]
        //public ActionResult RecreateUser()
        //{
        //    return PartialView();
        //}

        //[AuthorizeGroup(Group = "Super")]
        //[HttpPost]
        //public ActionResult RecreateUser(RecreateUserModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (FormsService.EmployeeExistWithoutUser(model.EmployeeId))
        //        {
        //            MembershipCreateStatus createResult = FormsService.ReCreateUser(model);
        //            if ( createResult == MembershipCreateStatus.Success)
        //            {
        //                ModelState.AddModelError(string.Empty, "创建成功");
        //                return PartialView();
        //            }
        //                ModelState.AddModelError(string.Empty , AccountValidation.ErrorCodeToString(createResult));
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("error", "不存在相应的员工ID或者该员工已经存在账户，请删除账户后再操作");
        //        }
        //    }

        //    return PartialView();
        //}




        //TODO: manual fill the blank,leavedate,on,off,and so on(superAccount)
        //用Logonmodel来做(superaccount) 对其他员工的修改
        //      Recreate user for employee(FINISHED)
    }
}